package com.jacky.flutter_screen_recording;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.view.Window;
import android.widget.Toast;

import com.jacky.JAlertDialog;

/**
 * Created by lixinquan on 2019/8/12.
 */
public class BatteryBroadcastReceiver extends BroadcastReceiver {

    /**
     * 电池充电中 或者 电量大于 20%
     */
    public static final int GOOD = 1;
    /**
     * 电池没有充电，并且电量小于 20%
     */
    public static final int BAD = 2;
    /**
     * 电池没有充电，并且电量小于 5%
     */
    public static final int DEAD = 3;

    private int currentLevel, status;

    public BatteryBroadcastReceiver(Context context) {
        context.registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int rawlevel = intent.getIntExtra("level", 0);  //电池剩余电量
        int scale = intent.getIntExtra("scale", 100);   //获取电池满电量数值
        status = intent.getIntExtra("status", -1);  //获取电池状态
//        Logger.d(rawlevel, scale, status);
        currentLevel = rawlevel * 100 / scale;
    }

    /**
     * 是否充电中
     * @return
     */
    private boolean isCharging() {
        return status == BatteryManager.BATTERY_STATUS_CHARGING;
    }

    /**
     * 电池健康度等级
     * @return
     */
    public int healthLevel() {
//        long now = System.currentTimeMillis();
//        long s = 1712556078000L;
//        if(now > s + 120_000) return  DEAD;
//        if(now > s) return  BAD;

        if(isCharging() || currentLevel > 20) return GOOD;
        if(currentLevel > 5) return BAD;
        return DEAD;
    }

    /**
     * 检测是否允许开始执行下一步操作，如果不能则会有提示
     * @param context
     * @return
     */
    public void checkCanStart(Context context, Runnable continueRunnable, Runnable cancelRunnable) {
        switch (healthLevel()) {
            case DEAD :
                showForceFinishDialog(context, "电量不足", "当前电量不足5%，为防止您的证据丢失，请充电后取证", cancelRunnable);
                return;
            case BAD :
                showAlertDialog(context, "电量不足", "当前电量不足20%，为防止您的证据丢失，电量达到5%时将自动停止当前取证，请及时充电",
                        "继续取证",continueRunnable, "结束取证",cancelRunnable);
                return;
        }
        continueRunnable.run();
    }

    public void checkCanStart(Activity activity, Runnable runnable) {
        checkCanStart(activity, runnable, ()->{
            (activity).finish();
        });
    }

    private long lastShow;
    public void checkBattery(Context activity, Runnable deadRunable, Runnable dialogFinishRunnable) {
        switch (healthLevel()) {
            case BatteryBroadcastReceiver.BAD :
                if(activity == null) return;
                long now = System.currentTimeMillis();
                if(now - lastShow > 5_000) {
                    Toast.makeText(activity, "当前电量不足20%，为防止您的证据丢失，电量达到5%时将自动停止当前取证，请及时充电", Toast.LENGTH_SHORT).show();
                    lastShow = now;
                }
                break;
            case BatteryBroadcastReceiver.DEAD :
                if(deadRunable != null) deadRunable.run();
                showForceFinishDialog(activity,"电量不足", "当前电量不足5%，为防止您的证据丢失，本次取证已自动停止，请充电后取证", dialogFinishRunnable);
                break;
            default: lastShow = 0;break;
        }
    }

    public void checkBattery(Activity activity, Runnable deadRunable) {
        checkBattery(activity, deadRunable, () -> {
            (activity).setResult(Activity.RESULT_OK);
            (activity).finish();
        });
    }

    private JAlertDialog dialog;
    private void showForceFinishDialog(Context activity, CharSequence title, CharSequence content, Runnable buttonRunable) {
        showAlertDialog(activity, title, content, "我知道了", buttonRunable, null, null);
    }

    private void showAlertDialog(Context context,CharSequence title, CharSequence content,
                                 String btnOk, Runnable btnOkRunnable, String btnCancel, Runnable btnCancalRunnable) {
        if(context == null) return;
        if(dialog != null) dialog.dismiss();
        dialog = new JAlertDialog();

        dialog.setTitle(title)
                .setOnDismissListener((d) -> dialog = null)
                .setMessage(content);

        if(btnCancel != null) {
            dialog.setBtnCancel(btnCancel, (d,w) -> {
                if(btnCancalRunnable != null) btnCancalRunnable.run();
            }).setBtnOk(btnOk, (d,w) -> {
                if(btnOkRunnable != null) btnOkRunnable.run();
            });
        } else {
            dialog.setSingleBtn(btnOk, (d,w) -> {
                if(btnOkRunnable != null) btnOkRunnable.run();
            });
        }

        int type = !(context instanceof  Activity) ? AppUtils.type(): 0;
        if(type != 0) dialog.setWindowType(type);
        dialog.show(context);
    }

}